#!/usr/bin/env python3

import re
from gradelib import *

r = Runner(save("xv6.out"))

@test(5, "sleep, no arguments")
def test_sleep_no_args():
    r.run_qemu(shell_script([
        'sleep'
    ]))
    r.match(no=["exec .* failed", "$ sleep\n$"])

@test(5, "sleep, returns")
def test_sleep_no_args():
    r.run_qemu(shell_script([
        'sleep',
        'echo OK'
    ]))
    r.match('^OK$', no=["exec .* failed", "$ sleep\n$"])

@test(10, "sleep, makes syscall")
def test_sleep():
    r.run_qemu(shell_script([
        'sleep 10',
        'echo FAIL'
    ]), stop_breakpoint('sys_sleep'))
    r.match('\\$ sleep 10', no=['FAIL'])

@test(20, "pingpong")
def test_pingpong():
    r.run_qemu(shell_script([
        'pingpong', 'echo OK'
    ]))
    r.match('^\\d+: received ping$', '^\\d+: received pong$', '^OK$')

@test(20, "primes")
def test_primes():
    r.run_qemu(shell_script([
        'primes', 'echo OK'
    ]))
    args = ['prime %d' % i for i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]]
    args.append('^OK$')
    r.match(*args)

@test(10, "find, in current directory")
def test_find_curdir():
    fn = random_str()
    r.run_qemu(shell_script([
        'echo > %s' % fn,
        'find . %s' % fn
    ]))
    r.match('./%s' % fn)

@test(10, "find, recursive")
def test_find_recursive():
    needle = random_str()
    dirs = [random_str() for _ in range(3)]
    r.run_qemu(shell_script([
        'mkdir %s' % dirs[0],
        'echo > %s/%s' % (dirs[0], needle),
        'mkdir %s/%s' % (dirs[0], dirs[1]),
        'echo > %s/%s/%s' % (dirs[0], dirs[1], needle),
        'mkdir %s' % dirs[2],
        'echo > %s/%s' % (dirs[2], needle),
        'find . %s' % needle
    ]))
    r.match('./%s/%s' % (dirs[0], needle),
            './%s/%s/%s' % (dirs[0], dirs[1], needle),
            './%s/%s' % (dirs[2], needle))

@test(19, "xargs")
def test_xargs():
    r.run_qemu(shell_script([
        'sh < xargstest.sh',
        'echo DONE',
    ], 'DONE'))
    matches = re.findall("hello", r.qemu.output)
    assert_equal(len(matches), 3, "Number of appearances of 'hello'")

@test(1, "time")
def test_time():
    check_time()
    
run_tests()
